<?php
namespace app\admin\controller;
use think\Controller;
use think\Db;
use think\Request;
class Administrator extends Common
{
    public function index()
    {
		// var_dump(__AD__);
       // return $this -> fetch();
    }
	public function managersList(){
		
		$user = Db::table('user') -> paginate(10);;
		$this -> assign('user',$user);
		return $this -> fetch();
	}
	public function managersAdd(){
		$data = Request::instance()->Param();
		$res = '';
		if(!empty($data)){
			$res = Db::table('user') -> where($data) -> find();
		}
		$this -> assign('res',$res);
		return $this -> fetch();
	}
	public function doManagersAdd(){
		$data = Request::instance()->Param();
		$file = request()-> file('photo');
		if($file != null){
			$info = $file->move(ROOT_PATH  . 'public'.DS. 'uploads'.DS.'managers');
			if($info){
				$photo =  '/uploads/managers/'.$info->getSaveName();
			}else{
				$this->error('图片上传失败');
			}
		$data['photo'] = $photo;
		}
		if($data['id']){
			$user = Db::table('user') -> where('id',$data['id']) -> find();
			$res['name'] = $data['name'] == $user['name']?$user['name']:$data['name'];
			$res['password'] = $data['password'] == $user['password']?$user['password']:md5($data['password']);
			$res['addtime'] = time();
			$res['position'] = $data['position'];
			$res['photo'] = $file?$photo:$data['photo'];
			// var_dump($res);die;
			$result = Db::table('user')-> where('id',$data['id']) -> update($res);
			if($file != null){
				unlink(ROOT_PATH  . 'public'.$user['photo']);
			}
			if($result){          
				//设置成功后跳转页面的地址，默认的返回页面是$_SERVER['HTTP_REFERER']
				$this->success('更新成功', 'Administrator/managersList');
			} else {
				//错误页面的默认跳转页面是返回前一页，通常不需要设置
				$this->error('更新失败');
			}
		}
		$data['addtime'] = time();
		$data['password'] = md5($data['password']);
		// 获取表单上传文件 例如上传了001.jpg
		
		
		$result = Db::table('user') -> insert($data);
		if($result){          
			//设置成功后跳转页面的地址，默认的返回页面是$_SERVER['HTTP_REFERER']
			$this->success('新增成功', 'Administrator/managersList');
        } else {
			//错误页面的默认跳转页面是返回前一页，通常不需要设置
			$this->error('新增失败');
		}
	}
	public function managersDelete(){
		$data = Request::instance()->Param();
		$result = Db::table('user') -> where($data) -> delete();
		if($result){          
			//设置成功后跳转页面的地址，默认的返回页面是$_SERVER['HTTP_REFERER']
			$this->success('删除成功', 'Administrator/managersList');
        } else {
			//错误页面的默认跳转页面是返回前一页，通常不需要设置
			$this->error('删除失败');
		}
	}
}
